package com.engine.wei.base;

import android.app.Application;
import android.content.Context;

import androidx.annotation.NonNull;
import androidx.lifecycle.ProcessLifecycleOwner;

import com.alibaba.android.arouter.launcher.ARouter;
import com.engine.wei.base.utils.ActivityStackManager;
import com.engine.wei.base.utils.ResourceUtils;
import com.engine.wei.base.utils.UiUtils;
import com.engine.wei.base.utils.log.LogManager;
import com.engine.wei.base.utils.log.LogUtils;
import com.engine.wei.base.utils.rxjava.RxUtils;
import com.tencent.mmkv.MMKV;

import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Predicate;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;


/**
 * 作者:赵若位
 * 时间:2021/8/26 15:51
 * 功能:
 */
public class FrameManager {

    private FrameManager() {

    }

    public static void init(@NonNull Application application,InitListener listener) {
        if (null != application) {
            if (BuildConfig.DEBUG) {
                ARouter.openLog();
                ARouter.openDebug();
                ARouter.setLogger(new LogUtils());
            }
            ARouter.init(application); // 尽可能早，推荐在Application中初始化
            MMKV.initialize(application);
            LogManager.init(application, null, BuildConfig.DEBUG);
            //监听Application的生命周期，前后台切换
            ActivityStackManager activities = ActivityStackManager.getInstance();
            application.registerActivityLifecycleCallbacks(activities);
            ProcessLifecycleOwner.get().getLifecycle().addObserver(activities);
            UiUtils.init(application);
            ResourceUtils.init(application);
            RxJavaPlugins.setErrorHandler(throwable -> LogUtils.e("Rxjava:" + throwable.getMessage()));
            if (null != listener) {
                listener.initSyncListener(application.getApplicationContext());
            }

            Observable.timer(1500, TimeUnit.MILLISECONDS)
                    .filter(aLong -> null == listener).compose(RxUtils.schedulers())
                    .subscribe(aLong -> listener.initAsynListener(application));
        }
    }

    public static void init(@NonNull Application application) {
        init(application, null);
    }


    public interface InitListener {
        void initSyncListener(Context context);

        void initAsynListener(Context context);
    }
}
